package com.gqzm.iaas.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.gqzm.iaas.domain.bo.BizException;
import com.gqzm.iaas.enums.ErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.stream.Collectors;

/**
 * @ClassName: {@link ExceptionInterceptor}
 * @description: 异常拦截器
 * @author: peter qin
 * @date: 2023 07 17
 * @version: 1.0
 **/
@Slf4j
@RestControllerAdvice
public class ExceptionInterceptor {


    /**
     * 捕获业务异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler({BizException.class})
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public String bizException(BizException e) {
        log.error("统一拦截异常",e);
        JSONObject result = new JSONObject();
        result.put("error_code", e.getErrorCode());
        result.put("message", e.getMessage());
        return result.toJSONString();
    }


    /**
     * 请求参数校验异常拦截
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public String validateException(MethodArgumentNotValidException e) {
        log.error("参数校验异常", e);
        JSONObject result = new JSONObject();
        result.put("error_code", ErrorCode.BASE_FAILED.getErrorCode());
        result.put("message", e.getBindingResult().getAllErrors()
                .stream()
                .map(ObjectError::getDefaultMessage)
                .collect(Collectors.joining(";")));
        return result.toJSONString();
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public String basicException(Exception e) {
        log.error("操作失败", e);
        JSONObject result = new JSONObject();
        result.put("error_code", ErrorCode.BASE_FAILED.getErrorCode());
        result.put("message", "操作失败");
        return result.toJSONString();
    }


}
